package com.gongpingjialoan.activity.sell;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.SellCarDetailActivity;
import com.gongpingjialoan.activity.car.SellCarHistoryActivity;
import com.gongpingjialoan.activity.main.BaseScrollFragment;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.SellCarHistoryAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessHistory;
import com.gongpingjialoan.bean.PlatBean;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.DhUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/9/5.
 */
public class SellCarDelarsFragment extends BaseScrollFragment implements View.OnClickListener, NetDataJson.OnNetDataJsonListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {


    private View view;

    private PullToRefreshListView pullToRefreshListView;


    private ListView listView;

    private View footView, deleteView, nocarView;

    public List<AssessHistory> mAssessHistories;

    private NetDataJson mNetDataJson;

    private NetDataJson deleteNetDataJson;

    private SellCarHistoryAdapter mSellCarHistoryAdapter;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;

    private TextView deleteTextView;

    private boolean isEdit = false;

    private boolean chooseAll = true;

    private int height;

    private SellCarHistoryActivity sellCarActivity;

    private Button sellButton, deleteButton;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        isScrollPage = true;
        action = "my_sellRecord_plat";
        view = inflater.inflate(R.layout.sell_car_fragment, null);
        sellCarActivity = (SellCarHistoryActivity) getActivity();
        height = DhUtil.dip2px(getActivity(), 80);
        sellButton = (Button) view.findViewById(R.id.sell_button);
        deleteView = view.findViewById(R.id.delete_view);
        deleteButton = (Button) view.findViewById(R.id.delete);
        deleteTextView = (TextView) view.findViewById(R.id.delete_all);
        footView = LayoutInflater.from(getActivity()).inflate(R.layout.listview_footview, null);
        nocarView = view.findViewById(R.id.nocar);
        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        mAssessHistories = new ArrayList<>();
        mSellCarHistoryAdapter = new SellCarHistoryAdapter(mAssessHistories, getActivity());
        listView = pullToRefreshListView.getRefreshableView();
        listView.setClipToPadding(false);
        listView.addFooterView(footView);
        listView.setAdapter(mSellCarHistoryAdapter);
        listView.setOnItemClickListener(this);
        listView.removeFooterView(footView);
        sellButton.setOnClickListener(this);
        deleteView.setOnClickListener(this);
        deleteButton.setOnClickListener(this);
        deleteTextView.setOnClickListener(this);
        mNetDataJson = new NetDataJson(this);


        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 300);
        return view;
    }


    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        nocarView.setVisibility(View.GONE);
        pullToRefreshListView.setVisibility(View.VISIBLE);
        updateData();

    }


    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.addParam("page", mPage);
        mNetDataJson.addParam("record_type", "sell_car");
        mNetDataJson.setUrl(API.collectHistory);
        mNetDataJson.request("get");
    }


    @Override
    public void onLastItemVisible() {
        if (!mHasMore) {
            return;
        }

        if (!mIsLoadingMore && mHasMore) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            mIsLoadingMore = true;
            mPage++;
            updateData();
        }
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) return;
        AssessHistory carSource = (AssessHistory) view.getTag(R.id.tag_second);
        if (isEdit) {
            carSource.isDelete = !carSource.isDelete;
            mSellCarHistoryAdapter.notifyDataSetChanged();
        }else {
            Intent intent = new Intent(getActivity(), SellCarDetailActivity.class);
            intent.putExtra("typevalue", carSource.car_id);
            getActivity().startActivity(intent);
        }
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        JSONArray jsonArray = null;
        if (isRefresh) {
            mAssessHistories.clear();
            mSellCarHistoryAdapter.setData(mAssessHistories);
        }
        try {
            jsonArray = json.getJSONArray("records");
            if (0 == jsonArray.length()) {
                mIsLoadingMore = false;
                nocarView.setVisibility(View.VISIBLE);
                pullToRefreshListView.onRefreshComplete();
                sellCarActivity.setEditVis(false , 0 );
                pullToRefreshListView.setVisibility(View.GONE);
                return;
            }

            for (int i = 0; i < jsonArray.length(); i++) {
                AssessHistory ah = new AssessHistory();
                JSONObject object = jsonArray.getJSONObject(i);
                ah.record_id = object.getString("record_id");
                ah.car_id = object.getString("car_id");
                ah.title = object.getString("title");
                ah.brand_slug = object.getString("brand_slug");
                ah.model_slug = object.getString("model_slug");
                ah.model_detail_slug = object.getString("model_detail_slug");
                ah.create_time = object.getString("create_time");
                ah.car_status = object.getString("car_status");
                ah.plat_counts = object.getString("plat_counts");
                ah.publish_days = object.getString("publish_days");
                ah.replied_plat_num = object.getString("replied_plat_num");
                ah.not_replied_plat_num = object.getString("not_replied_plat_num");
                ah.sell_type = object.getString("sell_type");
                ah.platsJSONArray = object.getJSONArray("new_replied_plats");
                JSONArray platList = object.getJSONArray("plat_list");
                int size = platList.length();
                List<PlatBean> platBeans = new ArrayList<>(size);
                if (size > 0) {
                    PlatBean titlePlatBean = new PlatBean();
                    titlePlatBean.setUpdate_time("日期");
                    titlePlatBean.setPlat_name("发布平台");
                    titlePlatBean.setStatus_str("状态");
                    platBeans.add(titlePlatBean);
                }
                for (int j = 0; j < size; j++) {
                    PlatBean platBean = new PlatBean();
                    JSONObject js = platList.getJSONObject(j);
                    platBean.setPlat_name(js.getString("plat_name"));
                    platBean.setStatus_str(js.getString("status_str"));
                    platBean.setUpdate_time(js.getString("update_time"));
                    platBeans.add(platBean);
                }
                ah.plat_list = platBeans;
                mAssessHistories.add(ah);
            }
            int page_num = json.getInt("total_page");
            if (page_num == mPage) {
                mHasMore = false;
            }
        } catch (JSONException e) {
            mIsLoadingMore = false;
            Toast.makeText(getActivity(), "数据异常，请稍后再试", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            sellCarActivity.setEditVis(false , 0 );
            return;
        }
        mSellCarHistoryAdapter.setData(mAssessHistories);
        if (mAssessHistories.size() > 0) {
            sellCarActivity.setEditVis(true , 0);
        } else {
            sellCarActivity.setEditVis(false , 0);
        }
        pullToRefreshListView.onRefreshComplete();
        //editTextView.setVisibility(View.VISIBLE);
        mIsLoadingMore = false;

   /*     mGuideTag = "SellCarHistoryActivity";
        setGuideResId(R.drawable.sellrecord_guide);
        addGuideImage();*/
    }


    @Override
    public void onClick(View v) {
        if (v == deleteTextView) {
            for (AssessHistory assessHistory :
                    mAssessHistories) {
                assessHistory.isDelete = chooseAll;
            }
            mSellCarHistoryAdapter.setData(mAssessHistories);
            deleteTextView.setText(chooseAll ? "反选" : "全选");
            chooseAll = !chooseAll;

        } else if (v == sellButton) {
            Intent intent = new Intent(getActivity(), MainActivity.class);
            intent.putExtra("type", "sell_car");
            startActivity(intent);
        } else if (v == deleteButton) {
            delete();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
        if (deleteNetDataJson != null) {
            deleteNetDataJson.cancelTask();
            deleteNetDataJson = null;
        }

    }

    private void delete() {
        final String deleteId = getDeleteIds();
        if ("".equals(deleteId)) {
            return;
        }
        AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
        ab.setTitle("删除记录");
        ab.setMessage("确定要删除所选择的记录吗?");
        ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (deleteNetDataJson == null) {
                    deleteNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                        @Override
                        public void onDataJsonError(String errorMessage) {
                            sellCarActivity.loadingDialog.dismiss();
                            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onDataJsonUpdate(JSONObject json) {
                            sellCarActivity.loadingDialog.dismiss();
                            //   editTextView.setText("编辑");
                            isEdit = false;
                            deleteView.setVisibility(View.GONE);
                            mSellCarHistoryAdapter.setEdit(isEdit);
                            Toast.makeText(getActivity(), "删除成功!", Toast.LENGTH_SHORT).show();
                            pullToRefreshListView.setRefreshing();
                        }
                    });
                }
                deleteNetDataJson.addParam("record_type", "sell_car");
                deleteNetDataJson.addParam("ids", deleteId);
                deleteNetDataJson.setUrl(API.deleteCollectCar);
                deleteNetDataJson.request("post");
                sellCarActivity.loadingDialog.show();
            }
        });
        ab.create().show();

    }


    //获取要删除的IDS
    private String getDeleteIds() {
        StringBuilder sb = new StringBuilder();
        for (AssessHistory assessHistory :
                mAssessHistories) {
            if (assessHistory.isDelete) {
                sb.append(assessHistory.record_id + ",");
            }
        }
        return sb.toString();
    }

    public void showEdit(TextView view) {
        if (mAssessHistories.size() > 0) {
            isEdit = !isEdit;
            view.setText(isEdit ? "取消" : "编辑");
            listView.setPadding(0, 0, 0, isEdit ? height : 0);
            deleteView.setVisibility(isEdit ? View.VISIBLE : View.GONE);
            mSellCarHistoryAdapter.setEdit(isEdit);
        }
    }


    public void cancle(TextView view) {
        if (isAdded()) {
            isEdit = false;
            view.setText("编辑");
            deleteView.setVisibility(View.GONE);
            mSellCarHistoryAdapter.setEdit(isEdit);
        }
    }


}
